package com.caltco.cargo.ops.common.utils;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.taobao.api.FileItem;
import com.caltco.cargo.ops.common.exception.RRException;
import com.caltco.cargo.ops.common.vo.CardMessageVo;
import com.caltco.cargo.ops.common.vo.LinkMessageVo;
import com.caltco.cargo.ops.common.vo.OAMessageVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * description: DingTalkUtil
 * date: 2023/3/16 9:32
 * author: yehao
 * version: 1.0
 */
@Component
public class DingTalkUtil {

    @Value("${dd.appkey}")
    private String appkey;

    @Value("${dd.appsecret}")
    private String appsecret;

    @Value("${dd.agentid}")
    private String agentid;

    /**
     * 获取企业内部应用的access_token
     */
    public String getToken() {
        String accessToken = "";
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
            OapiGettokenRequest request = new OapiGettokenRequest();
            request.setAppkey(appkey);
            request.setAppsecret(appsecret);
            request.setHttpMethod("GET");
            OapiGettokenResponse response = client.execute(request);
            accessToken = response.getAccessToken();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return accessToken;
    }

    /**
     * 通过免登码获取用户信息
     */
    public String getUserinfo(String code, String access_token) {
        String userid = "";
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getuserinfo");
            OapiV2UserGetuserinfoRequest req = new OapiV2UserGetuserinfoRequest();
            req.setCode(code);
            OapiV2UserGetuserinfoResponse rsp = client.execute(req, access_token);
            userid = rsp.getResult().getUserid();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return userid;
    }

    /**
     * 查询用户详情
     */
    public OapiV2UserGetResponse.UserGetResponse getUserDetail(String userid, String access_token) {
        OapiV2UserGetResponse.UserGetResponse result = null;
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
            OapiV2UserGetRequest req = new OapiV2UserGetRequest();
            req.setUserid(userid);
            req.setLanguage("zh_CN");
            OapiV2UserGetResponse rsp = client.execute(req, access_token);
            result = rsp.getResult();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 上传媒体文件
     */
    public String uploadFile(String fileUrl, String fileType) {
        String mediaId = "";
        try {
            String token = getToken();
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/media/upload");
            OapiMediaUploadRequest req = new OapiMediaUploadRequest();
            req.setType(fileType);
            // 要上传的媒体文件
            FileItem item = new FileItem(fileUrl);
            req.setMedia(item);
            OapiMediaUploadResponse rsp = client.execute(req, token);
            mediaId = rsp.getMediaId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mediaId;
    }

    /**
     * 发送文本消息通知
     */
    public Long sendMessageTypeText(String userIdList, String content) {
        String access_token = getToken();
        OapiMessageCorpconversationAsyncsendV2Response rsp = null;
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
            OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
            request.setAgentId(Long.parseLong(agentid));
            request.setUseridList(userIdList);
            request.setToAllUser(false);

            OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
            msg.setMsgtype("text");
            msg.setText(new OapiMessageCorpconversationAsyncsendV2Request.Text());
            msg.getText().setContent(content);
            request.setMsg(msg);
            rsp = client.execute(request, access_token);
        } catch (Exception e) {
            throw new RRException(rsp.getErrmsg());
        }
        return rsp.getErrcode();
    }

    /**
     * 发送图片消息通知
     */
    public Long sendMessageTypeImage(String userIdList, String mediaId) {
        String access_token = getToken();
        OapiMessageCorpconversationAsyncsendV2Response rsp = null;
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
            OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
            request.setAgentId(Long.parseLong(agentid));
            request.setUseridList(userIdList);
            request.setToAllUser(false);

            OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
            msg.setMsgtype("image");
            msg.setImage(new OapiMessageCorpconversationAsyncsendV2Request.Image());
            msg.getImage().setMediaId(mediaId);
            request.setMsg(msg);
            rsp = client.execute(request, access_token);
        } catch (Exception e) {
            throw new RRException(rsp.getErrmsg());
        }
        return rsp.getErrcode();
    }

    /**
     * 发送文件消息通知
     */
    public Long sendMessageTypeFile(String userIdList, String mediaId) {
        String access_token = getToken();
        OapiMessageCorpconversationAsyncsendV2Response rsp = null;
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
            OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
            request.setAgentId(Long.parseLong(agentid));
            request.setUseridList(userIdList);
            request.setToAllUser(false);

            OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
            msg.setMsgtype("file");
            msg.setFile(new OapiMessageCorpconversationAsyncsendV2Request.File());
            msg.getFile().setMediaId(mediaId);
            request.setMsg(msg);
            rsp = client.execute(request, access_token);
        } catch (Exception e) {
            throw new RRException(rsp.getErrmsg());
        }
        return rsp.getErrcode();
    }

    /**
     * 发送链接消息通知
     */
    public Long sendMessageTypeLink(LinkMessageVo params) {
        String access_token = getToken();
        OapiMessageCorpconversationAsyncsendV2Response rsp = null;
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
            OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
            request.setAgentId(Long.parseLong(agentid));
            request.setUseridList(params.getUserIdList());
            request.setToAllUser(false);

            OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
            msg.setMsgtype("link");
            msg.setLink(new OapiMessageCorpconversationAsyncsendV2Request.Link());
            msg.getLink().setTitle(params.getTitle());
            msg.getLink().setText(params.getContent());
            msg.getLink().setMessageUrl(params.getMessageUrl());
            msg.getLink().setPicUrl(params.getPicUrl());
            request.setMsg(msg);
            rsp = client.execute(request, access_token);
        } catch (Exception e) {
            throw new RRException(rsp.getErrmsg());
        }
        return rsp.getErrcode();
    }

    /**
     * 发送MarkDown通知
     */
    public Long sendMessageTypeMarkdown(String userIdList,String text,String title) {
        String access_token = getToken();
        OapiMessageCorpconversationAsyncsendV2Response rsp = null;
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
            OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
            request.setAgentId(Long.parseLong(agentid));
            request.setUseridList(userIdList);
            request.setToAllUser(false);

            OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
            msg.setMsgtype("markdown");
            msg.setMarkdown(new OapiMessageCorpconversationAsyncsendV2Request.Markdown());
            msg.getMarkdown().setText(text);
            msg.getMarkdown().setTitle(title);
            request.setMsg(msg);
            rsp = client.execute(request, access_token);
        } catch (Exception e) {
            throw new RRException(rsp.getErrmsg());
        }
        return rsp.getErrcode();
    }

    /**
     * 发送ActionCard通知
     */
    public Long sendMessageTypeActionCard(CardMessageVo params) {
        String access_token = getToken();
        OapiMessageCorpconversationAsyncsendV2Response rsp = null;
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
            OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
            request.setAgentId(Long.parseLong(agentid));
            request.setUseridList(params.getUserIdList());
            request.setToAllUser(false);

            OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
            msg.setMsgtype("action_card");
            msg.setActionCard(new OapiMessageCorpconversationAsyncsendV2Request.ActionCard());
            msg.getActionCard().setTitle(params.getTitle());
            msg.getActionCard().setMarkdown(params.getMarkdown());
            msg.getActionCard().setSingleTitle(params.getSingleTitle());
            msg.getActionCard().setSingleUrl(params.getMessageUrl());
            request.setMsg(msg);
            rsp = client.execute(request, access_token);
        } catch (Exception e) {
            throw new RRException(rsp.getErrmsg());
        }
        return rsp.getErrcode();
    }

    /**
     * 发送OA通知
     */
    public Long sendMessageTypeOA(OAMessageVo params) {
        String access_token = getToken();
        OapiMessageCorpconversationAsyncsendV2Response rsp = null;
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
            OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
            request.setAgentId(Long.parseLong(agentid));
            request.setUseridList(params.getUserIdList());
            request.setToAllUser(false);

            OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
            msg.setOa(new OapiMessageCorpconversationAsyncsendV2Request.OA());
            msg.getOa().setHead(new OapiMessageCorpconversationAsyncsendV2Request.Head());
            msg.getOa().getHead().setText(params.getHeadText());
            msg.getOa().setBody(new OapiMessageCorpconversationAsyncsendV2Request.Body());
            msg.getOa().getBody().setContent(params.getBodyText());
            msg.setMsgtype("oa");
            request.setMsg(msg);
            rsp = client.execute(request, access_token);
        } catch (Exception e) {
            throw new RRException(rsp.getErrmsg());
        }
        return rsp.getErrcode();
    }


}
